<?php

namespace app\controller;

use app\helper\JwtHelper;
use app\model\User;
use support\Request;

class UserController
{
    /**
     * 定义无需鉴权的函数
     * @var array
     */
    protected $noNeedLogin = ['login'];

    /**
     * 登录返回JWT
     * @param \support\Request $request
     * @return \support\Response
     */
    public function login(Request $request)
    {
        if ($request->method() == "POST") {
            $loginData = $request->post();
            if (isset($loginData['username']) && isset($loginData['password'])) {
                $loginResult = User::where(['username' => $loginData['username'], 'password' => md5($loginData['password'])])->findOrEmpty();
                if (!$loginResult->isEmpty()) {
                    $payload = [
                        "nickname" => $loginResult['nickname'],
                        "name" => $loginResult['username'],
                        "password" => $loginResult['password'],
                    ];
                    $jwtController = new JwtHelper();
                    $jwt = $jwtController->encode($payload);
                    return json(["code" => 200, "msg" => "登录成功", "data" => $jwt]);
                } else {
                    return json(["code" => 400, "msg" => "账号密码错误"]);
                }

            } else {
                return json(["code" => 400, "msg" => "用户名/密码不能为空"]);
            }
        }
        return json(["code" => 400, "msg" => "请用POST请求"]);
    }

    /**
     * 修改账号信息，需要JWT鉴权
     * @param \support\Request $request
     * @return \support\Response
     */
    public function update(Request $request)
    {
        if ($request->method() == "POST") {
            $data = $request->post();
            try {
                $data['password'] = md5($data['password']);
                User::update($data);
                return json(["code" => 200, "msg" => "更新成功"]);
            } catch (\Exception $e) {
                return json(["code" => 400, "msg" => "更新失败，请检查"]);
            }
        }
        return json(["code" => 400, "msg" => "请用POST请求"]);
    }

}
